package com.log.search.util;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {
    private static List<String> errorList = new ArrayList();
    static {
    }
    /**
     * 把多个空格替换成一个新的字符串如 a 5   8a    47=>a 5 8a 47
     * @param str
     * @param newStr
     * @return
     */

    public static String replaceBlank(String str, String newStr){
        Pattern p = Pattern.compile("\\s+");
        Matcher m = p.matcher(str);
        str= m.replaceAll(newStr);
        return str;
    }
    /**
     * 校验非法字符
     * @param str
     * @return
     */
    public static boolean valiErrorStr(String str){
        for (String s : errorList) {
            if(str.contains(s)){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取ip
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
